package com.qf.lja.servlet;

import com.qf.lja.dao.ProductDao;
import com.qf.lja.enity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.math.BigDecimal;


@WebServlet(urlPatterns = "/AddProduct")
@MultipartConfig
public class AddProductServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //utf-8
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");


        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.sendRedirect("login.jsp");
        }

        String productName = request.getParameter("productName");
        String price = request.getParameter("price");
        String inventory = request.getParameter("inventory");
        String description = request.getParameter("description");
        //图片处理
        Part part = request.getPart("imageUrl");
//        String fileName = part.getSubmittedFileName();

        String cd = part.getHeader("Content-Disposition");
        String temp = cd.substring(cd.lastIndexOf("=") + 1).trim();
        String fileName = temp.substring(1, temp.length() - 1);
        String path = "D:\\ideacode\\newpro\\web\\image\\";
        path += fileName;
        part.write(path);

        //打印
        System.out.println(productName);
        System.out.println(price);
        System.out.println(inventory);
        System.out.println(description);

        ProductDao productDao = new ProductDao();
        productDao.addProduct(productName, new BigDecimal(price), fileName,
                4, Integer.parseInt(inventory), 1, description);

        //跳转
        response.sendRedirect("productAdmin");
    }

}